#服务的实现
import dao, utils, entities

def user_login(name: str, pwd: str)->str:
    user_id = dao.get_user_id(name, pwd)
    if user_id==None:
        raise Exception("Invalid user name or password.")
    session:entities.Session = dao.create_session(user_id, entities.Session.OT_USER)
    if session:
        return session.token
    raise Exception("Create user session failed.")

def device_verify(key: str)->str:
    device_id = dao.get_device_id(key)
    if device_id == None:
        raise Exception("Invalid device key.")
    session:entities.Session = dao.create_session(device_id, entities.Session.OT_DEVICE)
    if session:
        return session.token

def get_device_id_by_token(token: str)->str:
    session = dao.get_session(token, entities.Session.OT_DEVICE)
    if session:
        return session.obj_id
    else:
        return None

def get_device_is_online(device_id: str)->bool:
    session = dao.get_session_by_obj_id(obj_id=device_id, obj_type=entities.Session.OT_DEVICE)
    return session != None

def get_device_is_empty(device_id: str)->bool:
    data = dao.get_last_message_data(device_id=device_id, action='foodstate')
    if data and data.data:
        return data.data.get('empty')==True
    return False

def verify_device_token(token: str)->bool:
    session = dao.get_session(token, entities.Session.OT_DEVICE)
    if session:
        return True
    else:
        return False

def verify_user_token(token: str)->bool:
    session = dao.get_session(token, entities.Session.OT_USER)
    if session:
        return True
    else:
        return False

def get_user_id_by_token(token: str)-> str:
    session = dao.get_session(token=token, obj_type=entities.Session.OT_USER)
    if session:
        return session.obj_id
    return None

def get_devices_by_user(user_id: str)->dict:
    #获取用户拥有的设备
    devices = dao.get_devices_by_user(user_id)
    ret = []
    for device in devices:
        data = device.to_json()
        #获取设备是否在线，如果有会话就是在线
        data['online'] = get_device_is_online(device._id)
        data['empty'] = get_device_is_empty(device._id)
        data['type'] = entities.Device.get_type_data(device.type)
        ret.append(data)
    return ret

def get_device_by_id(device_id: str)->dict:
    #获取用户拥有的设备
    device = dao.get_device_by_id(device_id=device_id)
    if device:
        return device.to_json()
    return None

def device_beat(data: dict)->dict:
    #将数据写入数据库
    dd = entities.DeviceData()
    dd.from_json(data)
    dd.time = utils.now_str()
    _id = dao.insert_device_data(dd)
    #获取led灯状态
    state:entities.LEDState = dao.get_last_led_state()
    if state:
        return {"led_state": state.state}
    else:
        return {"led_state": False}

def bind_device(user_id: str, device_id: str):
    #给用户绑定设备，可以不是拥有者，比如共享给别人的设备
    user = dao.get_user_by_id(user_id=user_id)
    if user:
        if not (device_id in user.devices):
            #设备id在用户设备中不存在就添加
            user.devices.append(device_id)
            dao.update_user(user=user)
            return
        else:
            raise Exception(f'设备{device_id}已经与用户绑定')
    raise Exception(f'{user_id}不存在')

def active_device(user_id: str, active_code, device_name):
    #激活设备，设置设备的拥有者，如果设备已有拥有者会被顶掉
    device = dao.get_device_by_active_code(active_code=active_code)
    if device==None:
        raise Exception(f'设备激活码{active_code}错误')
    user = dao.get_user_by_id(user_id=user_id)
    if user==None:
        raise Exception(f'id为{user_id}的用户不存在')
    device.name = device_name #设备名称
    device.time = utils.now_str() #激活时间
    device.owner = user._id #更新设备拥有者
    dao.update_device(device=device)
    if not device._id in user.devices:
        user.add_device(device._id)
        dao.update_user(user=user)

def modify_device_name(device_id: str, device_name: str):
    #修改设备名称
    device = dao.get_device_by_id(device_id=device_id)
    if device:
        device.name = device_name
        dao.update_device(device=device)
    else:
        raise Exception(f'id{device_id}的设备不存在')

def send_message(data: dict):
    #发送消息
    msg = entities.MessageData()
    msg.from_json(data)
    msg.time = utils.now_str()
    dao.insert_message_data(msg)

def get_last_message(device_id: str, action: str):
    #获取最后的消息
    # if not entities.MessageData.check_sender(sender):
    #     raise Exception(f"参数sender的值{sender}错误")
    msg = dao.get_last_message_data(device_id=device_id, action= action)
    if msg:
        return msg.to_json()

def get_message_list(device_id: str, sender: str = None, action: str=None, page_size: int=20, page_no: int = 1):
    #获取消息列表
    count, msgs = dao.get_message_data_list(device_id=device_id,
                                     page_size=page_size,
                                     page_no=page_no,
                                     sender=sender,
                                     action=action)
    return {"count":count, "msgs":[msg.to_json() for msg in msgs]}

if __name__ == "__main__":
    #print(device_beat({'temperature':12, 'pressure':23.2323, 'votage':1.2332, 'position':10,'switch':True}))
    #print(get_device_data(None, None))
    #print(verify_user_token('66797e316972a06d9eccaaa4'))
    print(device_beat({
    "temperature": 76,
    "pressure": 99,
    "voltage": 14,
    "position": 44,
    "switch": False
}))